class Solution {
public:
    string longestPalindrome(string s) {
        int n = s.size(), begin = 0, maxlen = 0;
        for(int i = 0; i < n; ++i)
        {
            int left = i, right = i, cnt = 0; // 奇数长度拓展
            while(left >= 0 && right < n && s[left] == s[right])
            {
                --left;
                ++right;
                cnt = right - left - 1;
            }
            if(cnt > maxlen)
            {
                begin = left + 1;
                maxlen = cnt;
            }
 
            left = i, right = i + 1, cnt = 0; // 偶数长度拓展
            while(left >= 0 && right < n && s[left] == s[right])
            {
                --left;
                ++right;
                cnt = right - left - 1;
            }
            if(cnt > maxlen)
            {
                begin = left + 1;
                maxlen = cnt;
            }
        }
        return s.substr(begin, maxlen);
    }
};